package com.iweb.dao;

import com.iweb.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
 *作者：lth
 *时间：2020/8/11 17:59
 *描述：
 */
public class UserDaoImpl implements UserDao {
	private PreparedStatement pst;
	private Connection conn;
	private ResultSet rs;

	public UserDaoImpl(Connection connection) {
		this.conn = connection;
	}

	@Override
	public void save(User user) throws Exception {
		String sql = "insert into tb_user (userid,username,password,phone,balance) values (?,?,?,?,?)";

		pst = conn.prepareStatement(sql);
		pst.setString(1, user.getUserid());
		pst.setString(2, user.getUsername());
		pst.setString(3, user.getPassword());
		pst.setString(4, user.getUserid());
		pst.setDouble(5, 8000); //初始用户默认8000元
		pst.executeUpdate();
	}

	@Override
	public User findByUserId(String userid) throws Exception {
		User user = null;
		String sql = "select * from tb_user where userid = ?";
		pst = conn.prepareStatement(sql);
		pst.setObject(1, userid);
		rs = pst.executeQuery();

		while (rs.next()) {
			user = createInstance(rs);
		}
		return user;
	}

	//返回用户总数
	@Override
	public long selectCount() throws Exception {
		String sql = "select count(1) from tb_user";
		pst = conn.prepareStatement(sql);
		rs = pst.executeQuery();
		rs.next();
		return rs.getLong(1);
	}

	//用户商品结算
	@Override
	public Double checkout(String userid, Double price) {
		String sql = "select balance from tb_user where userid = ?";
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, userid);
			rs = pst.executeQuery();

			//如果查询不到结果，则直接返回null
			if (rs.next()) {
				//查询到的账户余额
				Double balance = rs.getDouble(1);

				//如果账户余额足够，则可以购买，并执行update语句
				if (balance >= price) {
					balance -= price;
					//更新账户余额
					sql = "update tb_user set balance = ? where userid = ?";
					pst = conn.prepareStatement(sql);
					pst.setDouble(1, balance);
					pst.setString(2, userid);
					pst.executeUpdate();

					//清空该用户的购物车
					sql="delete from tb_order where aid = ?";
					pst=conn.prepareStatement(sql);
					pst.setString(1,userid);
					pst.executeUpdate();

					return balance;
				} else { //如果账户余额不足，也返回null
					return null;
				}
			} else {
				return null;
			}

		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}

		return null;
	}

	private User createInstance(ResultSet rs) throws Exception {
		User user = new User();
		user.setUserid(rs.getString("userid"));
		user.setUsername(rs.getString("username"));
		user.setPassword(rs.getString("password"));
		user.setPhone(rs.getString("phone"));
		user.setBalance(rs.getDouble("balance"));
		return user;
	}
}
